<html>
<head>
  <script src="https://cdn.firebase.com/v0/firebase.js"></script>
  <script type='text/javascript' src='https://cdn.firebase.com/v0/firebase-simple-login.js'></script>
  <script type='text/javascript' src='https://login.persona.org/include.js'></script>
  <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
  <script src="http://www.parsecdn.com/js/parse-1.2.8.min.js"></script>
  <link rel="stylesheet" href="css/chat.css">
</head>
<body>
		<div id='messagesDiv'></div>
		
		<input type='text' id='messageInput' placeholder='Message...'>
		<script>
			var dirChat;
				//<input type='text' id='nameInput' placeholder='Name'>
				  var vars = [], hash;
				  var varf = [], hash;
			      var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('#');
			      
				    for(var i = 0; i < hashes.length; i++) {
				        hash = hashes[i].split('=');
				        vars.push(hash[0]);
				        vars[hash[0]] = hash[1];
				    }
				  //codigo de prueba de segundo usuario
			      var hashef = window.location.href.slice(window.location.href.indexOf('!') + 1).split('$');
				    for(var i = 0; i < hashef.length; i++) {
				        hash = hashef[i].split('=');
				        varf.push(hash[0]);
				        varf[hash[0]] = hash[1];

				    }
				    var nameFriend = varf["friend"];
				  //fin codigo de prueba
			     var email=vars["user"];
			     var userName;
			     var urlFirebase;
			     //Get the name of the user
			     Parse.$= jQuery;
			     Parse.initialize("gLxhWhhBK7SPLZ7Jevs6q2lcLBlhje3l3sQlyS0e", "nPvJsuTXpFeKvNyDjZg8ks8sYwt2nntVOi9hr91J");
			     
			    var UserRegister = Parse.Object.extend("Contact");
				var query = new Parse.Query(UserRegister);
				query.equalTo("email", email);
				query.find({
			  		success: function(results) {	
					      var contact = results[0];
					      userName = contact.get("name");
					      urlFirebase = 'https://wayf.firebaseio.com/';

						  // Get a reference to the root of the chat data.
						  var chatRef = new Firebase(urlFirebase);
						  
						  var auth = new FirebaseSimpleLogin(chatRef, function(error, user) {
							  if (!error) {
							    // Success!
							  }
							});
							auth.login('persona', {
						  		rememberMe: true
							});
						  	chatRef.child(userName+'&'+nameFriend).on('value', function fun(snapshotF){
							  	if(!snapshotF.val()){
							  		dirChat = nameFriend+'&'+userName;
							  	}
							  	else{
							  		//chatFinal = chatUser;
							  		dirChat = userName+'&'+nameFriend;
							  	}
							  	// Add a callback that is triggered for each chat message.
						  
						  chatRef.child(dirChat).limit(8).on('child_added', function (snapshot) {
						    var message = snapshot.val();
						    $('<div/>').text(message.text).prepend($('<em/>')
						      .text(message.name+': ')).appendTo($('#messagesDiv'));
						    $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
						  });
							 });
							 
						  // When the user presses enter on the message input, write the message to firebase.
						  keyboard();
						  function keyboard(){
						  $('#messageInput').keypress(function (e) {
						    if (e.keyCode == 13) {
						      var name = userName;
						      var text = $('#messageInput').val();
						      chatRef.child(dirChat).push({name:name, text:text});
						      $('#messageInput').val('');
						    }
						  });
						}
						  
						 
						  
			  
			  },
					 error: function(results, error) {
			            alert("Error: " + error.code + " " + error.message);
			          }
				});
		</script>
	</body>
</html>